package br.com.projetosivan.servlet;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.com.projetosivan.controller.CarrinhoController;
import br.com.projetosivan.model.Produto;
import br.com.projetosivan.pagamento.PagamentoHandler;
import br.com.uol.pagseguro.domain.Item;
import br.com.uol.pagseguro.domain.ShippingType;

/**
 * Servlet implementation class PagamentoSvlt
 */
public class PagamentoSvlt extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PagamentoSvlt() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
	
	private void processRequest(HttpServletRequest request, HttpServletResponse response){
		PagamentoHandler ph = new PagamentoHandler();
		
		HttpSession session = request.getSession();
		
		CarrinhoController car = (CarrinhoController) session.getAttribute("carrinhoController");  
		
		List<Produto> produtos = car.getCarrinho().getProdutos();
		List<Item> itens = new ArrayList<Item>();
		for(int i = 0 ; i < produtos.size() ; i++){
			Produto produto = produtos.get(i);
			Item item = new Item();
			item.setAmount(roundingValue(new BigDecimal(produto.getPreco()), 2));
			item.setDescription(produto.getNome());
			item.setQuantity(new Integer(1));
			item.setWeight(new Long(5));
			item.setShippingCost(roundingValue(new BigDecimal(0.0), 2));
			item.setId(produto.getId().toString());
			itens.add(item);
		}
		
		URL url = ph.efetuarPagamento(
				itens, "1234", ShippingType.NOT_SPECIFIED, 
				"Carlos da Silva", "carlosdasilva@uol.com.br", "48", "96085967");
	
		try {
			response.sendRedirect(url.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public BigDecimal roundingValue(BigDecimal value, int scale) {
		return value.setScale(scale, RoundingMode.HALF_UP);
	} 

}
